using NAnt.Core;
using NAnt.Core.Attributes;

namespace Lean.NantTasks.Deployment
{
    /// <summary>
    /// The <see cref="LogLevelTask"/>
    /// class is a NAnt task that is used to determine the logging level used to execute
    /// a set of child tasks.
    /// </summary>
    /// <remarks>This code was inspired from the blog post found at http://jayflowers.com/WordPress/?p=133</remarks>
    [TaskName("loglevel")]
    public class LogLevelTask : TaskContainer
    {
        private Level _logLevel;

        [TaskAttribute("level", Required = true)]
        public Level LogLevel {
            get { return _logLevel; }
            set { _logLevel = value; }
        }

        /// <summary>
        /// Executes the task.
        /// </summary>
        protected override void ExecuteTask()
        {
            Level oldLevel = Project.Threshold;
            AssignLogLevel(LogLevel);

            base.ExecuteTask();

            AssignLogLevel(oldLevel);
        }

        /// <summary>
        /// Assigns the log level.
        /// </summary>
        /// <param name="newLevel">The new level.</param>
        private void AssignLogLevel(Level newLevel)
        {
            // Loop through each logger
            foreach (IBuildListener listener in Project.BuildListeners)
            {
                IBuildLogger logger = listener as IBuildLogger;
                if (logger != null)
                {
                    logger.Threshold = newLevel;
                }
            }
        }
    }
}

